import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * This class performs word counting on a file
 * @author Mathieu Morel, Pradyut Pokuri, Emily Rice
 * @version 1.0
 */
public class FileWordCounter {

	private int wordCounter = 0;
	
	//Used to differentiate between file exists error and read privileges errors
	private boolean fileExists = false;
	
	public FileWordCounter() {
		super();
	}

	/**
	 * Method that counts and displays on the system's standard output the number of words existing in a file
	 * @param fileName the name of the passed file
	 * @param delims the regular expression of the delimiters
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public void wordCount(String fileName, String delims) throws IOException, FileNotFoundException {
		//Check if file with specified file name exists
		fileExists = (new File(fileName)).exists();
		
		//Using the Scanner class to tokenize, parse and count input
		Scanner s = null;
		
		try {
			s = new Scanner(
					new BufferedReader(
							new FileReader(fileName)));
			
			//Use the Scanner class's useDelimiter object to create tokens from input
			//broken up by specified delims
			s.useDelimiter(delims);
			
			while (s.hasNext()) {
				if(wordCounter == Integer.MAX_VALUE )
					//If word count equals max size of a Java int, print an error
					throw new Exception("Overflow");
				wordCounter++;
				s.next();
			}
			//Print result
			System.out.println("The result is: " + wordCounter +" words");
		} 
		catch(FileNotFoundException e){
			if(fileExists) //Privileges error
				System.out.println("ERROR: unable to read input file");
			else //File does not exist error
				System.out.println("ERROR: unable to process input file");
		}   
		catch (Exception e){
			if (e.getMessage() == "Overflow"){ //Exception if word count equals max int
				System.out.println("ERROR: file contains too many words");	
			}
				
 		} finally {
			if (s != null) {
				//Close at the end
				s.close();
				// and exit program
				System.exit(0);
			}	
		}	
	}
}
